package com.xpq.petserver.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;

public class JWTUtils {
    private static final String SIGN = "!QLJD@156da%Y";

    /**
     * 生成token串
     * @param userId 存入token的用户id
     * @return token
     */
    public static String getToken(String userId){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,3);//默认3天过期

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();
        //payload
        builder.withClaim("id", userId);

        String token = builder.withExpiresAt(instance.getTime())//指定过期时间
        .sign(Algorithm.HMAC256(SIGN));//sign

        return token;
    }

    /**
     * 验证token
     * @param token
     * @return
     * */
    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }

    /**
     * 获取token中payload
     * @param token
     * @return
     * */
    public static DecodedJWT getTokenInfo(String token){
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }

    /**
     * 获取用户id
     * @param token 传入的token
     * @return 用户id
     */
    public static String getUserId(String token) {
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token).getClaim("id").asString();
    }



}
